const canvas = document.getElementById("canvas1") as HTMLCanvasElement;
const context = canvas.getContext("2d") as CanvasRenderingContext2D;
const arr = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];

function render() {
  // 保存初始状态
  context.clearRect(0, 0, 800, 800);
  context.save();
  context.translate(400, 300);
  //   绘制文字
  for (let i = 0; i < 12; i++) {
    context.beginPath();
    let radius = ((Math.PI * 2) / 12) * i;
    // 将文字放置在园内
    let fontx = (200 - 50) * Math.cos(radius);
    let fonty = (200 - 50) * Math.sin(radius);
    context.font = "20px 宋体";
    context.fillText(`${arr[i]}`, fontx, fonty);
    context.closePath();
  }
  context.rotate(-(Math.PI / 180) * 90);
  context.save();
  context.arc(0, 0, 200, 0, 2 * Math.PI);
  context.lineWidth = 5;
  context.stroke();
  context.restore();
  context.save();

  // 绘制小时刻度
  for (let index = 0; index < 12; index++) {
    context.beginPath();
    context.rotate((Math.PI * 2) / 12);
    context.strokeStyle = "#333";
    context.lineWidth = 8;
    context.moveTo(170, 0);
    context.lineTo(190, 0);
    context.stroke();
    context.closePath();
  }
  context.restore();
  context.save();
  // 绘制分刻度
  for (let index = 0; index < 60; index++) {
    context.beginPath();
    context.rotate((Math.PI * 2) / 60);
    context.strokeStyle = "#333";
    context.lineWidth = 2;
    context.moveTo(180, 0);
    context.lineTo(190, 0);
    context.stroke();
    context.closePath();
  }

  context.restore();
  context.save();
  const time = new Date();
  let hour = time.getHours();
  const min = time.getMinutes();
  const second = time.getSeconds();
  hour = hour > 12 ? hour - 12 : hour;
  console.log(hour, min, second);

  // 绘制秒
  context.rotate(((Math.PI * 2) / 60) * second);
  context.beginPath();
  context.strokeStyle = "red";
  context.lineWidth = 3;
  context.moveTo(-30, 0);
  context.lineTo(160, 0);
  context.stroke();
  context.closePath();
  context.restore();
  context.save();
  // 绘制分
  context.rotate(((Math.PI * 2) / 60) * min + ((Math.PI * 2) / 3600) * second);

  context.beginPath();
  context.strokeStyle = "back";
  context.lineWidth = 5;
  context.moveTo(-30, 0);
  context.lineTo(140, 0);
  context.stroke();
  context.closePath();
  context.restore();
  context.save();

  // 绘制时
  context.rotate(
    ((Math.PI * 2) / 12) * hour +
      ((Math.PI * 2) / 12) * 60 * min +
      ((Math.PI * 2) / 12) * 3600 * second
  );
  context.beginPath();
  context.strokeStyle = "back";
  context.lineWidth = 8;
  context.moveTo(-30, 0);
  context.lineTo(100, 0);
  context.stroke();
  context.closePath();
  context.restore();

  context.restore();
  requestAnimationFrame(render);
}
render();
